
import { Button } from "antd";
import React, { useState } from "react";
import { useEffect } from "react";
import { useRef } from "react";
import { BrowserRouter, Route, Routes,Router,useNavigate,Link,Outlet } from "react-router-dom";

const Cavans1 = () => {
  const history = useNavigate()
   //判断是否绘制过
  const [isDrawed, setisDrawed] = useState(0);
  const cref = useRef("");
  const imgref = useRef("");
  //判断是否正在绘画的状态
  let isDrawing = false;
  //利用宽度特性将canvas画布清除，
  const handleCancel = () => {
   
    cref.current.width = cref.current.width;
    history('/')
  };
  //将canvas转为img图片
  const handleConfirm = () => {
    if (isDrawed > 1||isDrawed===0) {
      return;
    }
    // 第一种方法 采用data:application/octet-stream ,让浏览器识别为下载，有大小限制，12000*4000无法保存
    let image = new Image();
    image.src = cref.current.toDataURL({
      format: "image/png",
      quality: 1,
    });
    console.log(image.src);
    // var url = image.src.replace(
    //   /^data:image\/[^;]/,
    //   "data:application/octet-stream"
    // );
    image.style.height = "100px";
    image.style.width = "100px";
    image.style.display="block"
    imgref.current.appendChild(image);
   setisDrawed(isDrawed+1)
   //清除画布
   cref.current.width = cref.current.width;
    return;
    // window.open(url);
  };
  useEffect(() => {
    const ctx = cref.current.getContext("2d");
    // const ctx =cvs.getContext('2d')
    //    console.log(ctx)
    cref.current.addEventListener("mousedown", (e) => {
      isDrawing = true;
      setisDrawed(isDrawed+1)
      ctx.moveTo(e.offsetX, e.offsetY);
    });
    cref.current.addEventListener("mousemove", (e) => {
      if (isDrawing) {
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        // console.log(e);
      }
    });
    cref.current.addEventListener("mouseup", (e) => {
      isDrawing = false;
    });
  }, []);
  return (
    <>
      <h1>我是canvas</h1>
      <div className="imgContainer">
        <canvas
          ref={cref}
          width="500"
          height="500"
          id="cvs"
          style={{ border: "1px solid #f0b52b" }}
        ></canvas>
      </div>
      <div style={{ display: "flex", justifyContent: "right" }}>
        <Button
          type="primary"
          style={{ marginRight: "10px" }}
          onClick={handleConfirm}
        >
          确定
        </Button>
        <Button type="error" danger onClick={handleCancel}>
          取消
        </Button>
      </div>
      <div ref={imgref} >
      </div>
    </>
  );
};
export default Cavans1;
